package pkj.no.notetab.gui;

import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Tabs extends JTabbedPane implements ChangeListener {

	private ArrayList<Tab> tabs = new ArrayList<Tab>();
	private Tab plusTab = new Tab(this);

	final private String DEFAULT_TAB_STRING = "Default";

	public Tabs() {
		addDefaultTab();

		this.addChangeListener(this);
		setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
	}

	public Tab getActiveTab() {
		return tabs.get(this.getSelectedIndex());
	}

	public void addTab(Tab t) {
		tabs.add(t);
	}

	public void addDefaultTab() {
		addTab(new Tab(this, DEFAULT_TAB_STRING));
	}

	public void refresh() {
		int idx = getSelectedIndex();
		setTabs();
		setSelectedIndex(idx);
		
	}

	public void setTabs() {
		for (Tab t : tabs) {
			addTab(t.getName(), t);

		}
		addTab(plusTab.getName(), plusTab);
	}

	@Override
	public void stateChanged(ChangeEvent e) {
		JTabbedPane pane = (JTabbedPane) e.getSource();
		// If we click the + button.
		if (pane.getSelectedIndex() == tabs.size()) {

			addNewTab();
		}
	}

	public void addNewTab() {
		this.removeTabAt(tabs.size());
		addDefaultTab();
		setTabs();
		this.setSelectedIndex(tabs.size() - 1);
	}

	public Tab addNewTab(String name) {
		this.removeTabAt(tabs.size());
		Tab tab = new Tab(this, name);
		addTab(tab);
		setTabs();
		this.setSelectedIndex(tabs.size() - 1);
		return tab;
	}

	public void fileToTab(File f) throws IOException {
		
		// Check if the file is already opened.
		for(int i = 0; i < tabs.size(); i++){
			Tab t = tabs.get(i);
			if (t.getBelongsToFile() != null && t.getBelongsToFile().getAbsolutePath().equals(f.getAbsolutePath())){
				this.setSelectedIndex(i);
				refresh();
				return; // Exit method.
			}
		}
		//  Read in the file to textHolder.
		BufferedReader pw;
		BufferedReader br = new BufferedReader(new FileReader(f));
		StringBuilder sb = new StringBuilder();
		String line = br.readLine();
		while (line != null) {
			sb.append(line + "\n");
			line = br.readLine();
		}
		br.close();
		Tab tab = addNewTab(f.getName());
		tab.setSaved(true);

		tab.getTextArea().setText(sb.toString());
		tab.setBelongsToFile(f);

		refresh();
		this.setSelectedIndex(tabs.size() -1);
	}

	
	public ArrayList<Tab> getTabs(){
		return tabs;
	}
}
